<template>
    <el-container>
        <el-header style="height:auto;">
            <BlogsHead></BlogsHead>
        </el-header>
    </el-container>

    <div style="display: flex;">
        <div style="display: flex;flex-direction: column; width: 100%;justify-content: space-between;background-color:
        white;">

            <!-- <div style="display: flex;"> -->
            <!-- <div style="margin-left: 15%;"> -->
            <div style="display: flex;margin-left: 15%">
                <h2>{{ blogData.blogName }}</h2>
                <el-text class="mx-1" style="align-self: flex-end;margin-left: 2%;">{{ blogData.createTime
                    }}</el-text>
            </div>

            <div id="vditor" style="margin-top: 1%; width: 100%;margin-left: 15%"></div>

            <div style="margin-top: 2%;margin-left: 15%;">
                <el-text class="mx-1" size="large">发布评论：</el-text>
                <div style="display: flex;align-items: center;">
                    <el-input v-model="commentContent" style="width: 480px" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea" placeholder="Please input" />
                </div>
                <el-button type="primary" @click="AddComment" style="margin-top: 1%;">发布</el-button>
            </div>

            <div style="margin-top: 2%;margin-left: 15%;">
                <el-text class="mx-1" size="large">评论区：</el-text>
                <Comments v-for="item in comments" :key="item.id" :data="item" :parent="0"
                    :reply-details="item.replyDetails" :getComments="GetComments" />
            </div>
            <el-button style="margin-left: 15%;width: 30%;margin-top: 20%" v-if="blogData.userId == myUserId"
                @click="DelBlog">删除</el-button>
        </div>

        <AuthorDetails :data="blogData.userDetails" :userId=blogData.userId :tagsArr="blogData.tags"
            :youLike="blogData.youLike" :youFocus="blogData.youFocus" :youStar="blogData.youStar"
            :blogLikes="blogData.blogLikes" :blogStars="blogData.blogStars" :blogId="blogData.id"
            style="margin-right: 5%;" />
    </div>
</template>

<script setup>
import BlogsHead from '@/components/Blogs/BlogsHead.vue';
import { IsLoginIn } from '@/components/functions/IsLoginIn.vue';
import Vditor from 'vditor';
import "vditor/dist/index.css";
import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router'; // 引入路由
import { useRouter } from 'vue-router'; // 引入路由
import axios from 'axios'
import Comments from '@/components/Comments.vue';
import AuthorDetails from '@/components/AuthorDetails.vue';

const route = useRoute();

const router = useRouter();

const comments = ref([]);

const blogData = ref({
    blogName: '',
    createTime: '',
    userDetails: '',
    userId: ''
});

const blogId = ref('');

const commentContent = ref('');
const vditor = ref();

const myUserId = localStorage.getItem('userId');

function AddComment() {
    IsLoginIn();

    axios
        .post('/api/comment/add', {
            content: commentContent.value,
            blog_id: blogId.value,

        }, {
            headers: {
                'HOSHINO_T_KK': localStorage.getItem('userToken'),
            }
        })
        .then(response => {
            console.log(response);
            console.log(localStorage.getItem('userToken'));
            GetComments();
        })
        .catch(function (error) { // 请求失败处理
            console.log(error);
        });

}

function DelBlog() {
    IsLoginIn();

    axios
        .post('/api/blog/delUserBlog', {
            blog_id: blogId.value,

        }, {
            headers: {
                'HOSHINO_T_KK': localStorage.getItem('userToken'),
            }
        })
        .then(response => {
            console.log(response);
            console.log(localStorage.getItem('userToken'));
            router.push('/');
            // GetComments();
        })
        .catch(function (error) { // 请求失败处理
            console.log(error);
        });
}

function GetComments() {
    axios
        .post('/api/comment/blog', {
            blog_id: blogId.value,

        }, {
            headers: {
                'HOSHINO_T_KK': localStorage.getItem('userToken'),
            }
        })
        .then(response => {
            console.log(response);
            comments.value = response.data.data;
        })
        .catch(function (error) { // 请求失败处理
            console.log(error);
        });
}

function print() {
    vditor.value.setValue(blogData.value.content.toString())
}

// watch(blogData.value.content, (newVal) => {
//     vditor.value.setValue(newVal.toString())
// });

function GetBlogContent() {
    axios
        .post('/api/blog/getById', {
            blog_id: blogId.value,
        }, {
            headers: {
                'HOSHINO_T_KK': localStorage.getItem('userToken'),
            }
        })
        .then(response => {
            console.log(response);
            blogData.value = response.data.data;
            console.log(blogData.value.tags);
            // vditor.value.setValue(blogData.value.content.toString());
            setTimeout(() => {
                vditor.value.setValue(blogData.value.content.toString());
            }, 500);
        })
        .catch(function (error) { // 请求失败处理
            console.log(error);
        });
}

const IOptions = {
    cdn: "https://s4.zstatic.net/npm/vditor/",
    rtl: false,
    cache: {
        enable: false,
    },
    classes: {
        preview: "",
    },
    comment: {
        enable: false,
    },
    counter: {
        enable: false,
        type: "markdown",
    },
    customRenders: [],
    debugger: false,
    fullscreen: {
        index: 90,
    },
    height: "auto",
    hint: {
        delay: 200,
        emoji: {
            "+1": "👍",
            "-1": "👎",
            "confused": "😕",
            "eyes": "👀️",
            "heart": "❤️",
            "rocket": "🚀️",
            "smile": "😄",
            "tada": "🎉️",
        },
        // emojiPath: `${Constants.CDN}/dist/images/emoji`,
        extend: [],
        parse: true,
    },
    icon: "ant",
    lang: "zh_CN",
    mode: "sv",
    outline: {
        enable: true,
        position: "left",
    },
    placeholder: "请输入内容",
    preview: {
        actions: ["desktop", "tablet", "mobile", "mp-wechat", "zhihu"],
        delay: 1000,
        // hljs: Constants.HLJS_OPTIONS,
        // markdown: Constants.MARKDOWN_OPTIONS,
        // math: Constants.MATH_OPTIONS,
        maxWidth: 800,
        mode: "both",
        // theme: Constants.THEME_OPTIONS,
        render: {
            media: {
                enable: true,
            }
        }
    },
    link: {
        isOpen: true,
    },
    image: {
        isPreview: true,
    },
    resize: {
        enable: false,
        position: "bottom",
    },
    theme: "classic",
    toolbar: [

    ],
    toolbarConfig: {
        hide: true,
        pin: true,
    },
    typewriterMode: true,
    undoDelay: 800,
    // upload: {
    //     extraData: {},
    //     fieldName: "file[]",
    //     filename: (name: string) => name.replace(/\W/g, ""),
    //     linkToImgUrl: "",
    //     max: 10 * 1024 * 1024,
    //     multiple: true,
    //     url: "",
    //     withCredentials: false,
    // },
    value: '早上好',
    // value: blogValue,
    width: "1000px",
    // after: () => {
    //     that.vditor.insertValue("# 插入数据")
    //     //that.vditor.setValue("# 覆盖数据")

    // }
}

onMounted(() => {
    // const vditor = ref(new Vditor('vditor', IOptions));
    vditor.value = new Vditor('vditor', IOptions);
    blogId.value = route.query.id;

    // console.log(blogId.value);
    GetBlogContent();
    GetComments();
})
</script>

<style scoped>
#vditor :deep(.vditor-outline) {
    display: block !important;

}

#vditor :deep(.vditor-sv) {
    display: none !important;
}

#vditor :deep(.vditor-preview__action) {
    display: none !important;
}
</style>
